/**
 * Copyright (C), 2001-2031, www.bosssoft.com.cn
 * FileName: BaseContextHolder.java
 * Author: Camera
 * Date: 2024/8/5 12:28
 * Description:
 * <p>
 * History:
 * Date          Author   Version  Desc
 * 2024-01-01    bosssoft  1.0.0   initialize this file
 */
package com.bosssoft.common.token;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @className: BaseContextHolder
 * @description: 用于在请求处理过程中存储和检索用户上下文信息的线程局部存储类。
 * 此类利用ThreadLocal来保证线程安全，每个线程拥有独立的上下文信息。
 * @author: Camera
 * @date: 2024/8/512:28
 * @since 1.0
 **/
public class BaseContextHolder {
    /**
     * ThreadLocal变量，用于存储每个线程的上下文信息
     */
    private static final ThreadLocal<ConcurrentHashMap<String, Object>> CONTEXT_HOLDER =
            ThreadLocal.withInitial(ConcurrentHashMap::new);

    public static void setUserId(Long userId) {
        CONTEXT_HOLDER.get().put(BaseContextConstants.JWT_KEY_USER_ID, userId);
    }

    public static void set(String key, Object value) {
        CONTEXT_HOLDER.get().put(key, value);
    }

    public static void setTanentId(Long tenantId) {
        CONTEXT_HOLDER.get().put(BaseContextConstants.JWT_KEY_TANENT_ID, tenantId);
    }

    public static void setOrgId(Long orgId) {
        CONTEXT_HOLDER.get().put(BaseContextConstants.JWT_KEY_ORG_ID, orgId);
    }

    public static void setCompanyId(Long companyId) {
        CONTEXT_HOLDER.get().put(BaseContextConstants.JWT_KEY_COMPANY_ID, companyId);
    }

    public static void setAuthorities(String authorities) {
        CONTEXT_HOLDER.get().put(BaseContextConstants.JWT_KEY_AUTHORITIES, authorities);
    }

    public static void setToken(String token) {
        CONTEXT_HOLDER.get().put("token", token);
    }

    public static void setAccount(String account, List<Object> roleIdList) {
        CONTEXT_HOLDER.get().put("account", account);
        CONTEXT_HOLDER.get().put("roleIdList", roleIdList);
    }

    public static Long getUserId() {
        return (Long) CONTEXT_HOLDER.get().get(BaseContextConstants.JWT_KEY_USER_ID);
    }

    // 设置登录用户ID
    public static void setLoginUserId(Long userId) {
        CONTEXT_HOLDER.get().put("loginUserId", userId);
    }

    // 设置登录用户名
    public static void setLoginUserName(String userName) {
        CONTEXT_HOLDER.get().put("loginUserName", userName);
    }

    // 获取登录用户ID
    public static Long getLoginUserId() {
        return (Long) CONTEXT_HOLDER.get().get("loginUserId");
    }

    // 获取登录用户名
    public static String getLoginUserName() {
        return (String) CONTEXT_HOLDER.get().get("loginUserName");
    }

    // 清除当前线程的所有上下文信息
    public static void clearContext() {
        CONTEXT_HOLDER.get().clear();
    }


    public static void remove() {
        CONTEXT_HOLDER.remove();
    }

    private BaseContextHolder() {}
}